package org.jeecg.modules.cascv.image.service.merge.shipingui;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author;作者
 * @Date 2023/2/9 10:53
 * @Description :时频柜副柜
 * @Version
 */
@Slf4j
@Service
public class ShipingFuguiService extends ImageService {
    @Value("${imageurl}")
    private  String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;
    @Override
    public String idsNames() {
        return "6D9DH_71H";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");



        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }


        String dataFrames = jsonObject.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
       // dataFrames = (dataFrames.split(";")[1]).substring(0, 2).trim();
      //  dataFrames = dataFrames.substring(7,dataFrames.length()-10);
        StringBuilder queue = LaptopConstant.imageData.get(key);

        int[] intBuffer = new int[1000 * 1000];
        int k = 0;
        String packageno = dataFrames.substring(0, 4);
        int packageNo = Integer.parseInt(packageno);
        if("0000".equalsIgnoreCase(dataFrames.substring(0,4))&&queue==null){ //代表是图像的开始
            queue = new StringBuilder();
            dataFrames =  dataFrames.substring(12);
            queue.append(dataFrames);
        }else {
            dataFrames =  dataFrames.substring(12);
            queue.append(dataFrames);
        }
        LaptopConstant.imageData.put(key,queue);

        if(packageNo%500==0) {
            for (int j = 0; j < queue.length(); j += 2) {
                intBuffer[k++] = Integer.parseInt(queue.substring(j, j + 2), 16);
            }
            if (queue.length() == 1920 * 2) {
                //等于1926 * 2的话 说明是对接实时处理那块发下来的  用第一行的最后80字节来填补第二行的80字节
                for (int j = 1840; j < 2000; j += 2) {
                    intBuffer[k++] = Integer.parseInt(queue.substring(j, j + 2), 16);
                }
            }
            //合成图片
            int width = 1000;
            int height = 1000;


            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                long start = System.currentTimeMillis();
                String secondStr = jsonObject.getString("second");
                        long second = Long.parseLong(secondStr);
                        String subSecondStr = jsonObject.getString("subsecond");
                        secondStr = LaptopUtil.toDayHoursMinSec(second);

                        byte[] byteArr = new byte[intBuffer.length];
                        for (int i = 0; i < intBuffer.length; i++) {
                            byteArr[i] = (byte) intBuffer[i];
                        }
                        String idStr = IdWorker.getIdStr();
                        LaptopConstant.nativeImageIO.write(byteArr, height, width, "/data/images/", idStr + ".png", "png");
                        String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                        jsonObject.put("imageUrl", imageUrl);
                        System.out.println("imageUrl = " + imageUrl);
                        jsonObject.put("idsName", idsName);

                        //   String secondStr = conJson.getString("A1_FPR_MICU_APP1DATA_8_11_1").split(";")[1];
                        //  String subSecondStr = conJson.getString("A1_FPR_MICU_APP1DATA_12_13_1").split(";")[1];

                        String[] split = secondStr.split(":");
            jsonObject.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
            jsonObject.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));

                jsonObject.put("key", key);
                log.info("时频柜副柜"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

                return jsonObject;
            },taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);

            LaptopConstant.imageData.remove(key);

        }
        return null;
    }
    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("E:\\11图像数据\\cut2\\高精度\\6D9DH_71H.txt");
        ShipingFuguiService shipingFuguiService = new ShipingFuguiService();
        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string);

            shipingFuguiService.merge(jsonObject, "6D9DH_71H", "6D9DH_71H");
        }

    }
}
